package com.kou.backend.service.impl.file;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kou.backend.dao.*;
import com.kou.backend.dto.user.StoreFileResultDTO;
import com.kou.backend.entity.FileResourceDO;
import com.kou.backend.entity.FileTagDO;
import com.kou.backend.entity.FileTagMappingDO;
import com.kou.backend.entity.UserFileDO;
import com.kou.backend.error.CommonErrorEnum;
import com.kou.backend.exception.CommonException;
import com.kou.backend.request.file.UploadFileRequestDTO;
import com.kou.backend.service.FileStorageService;
import com.kou.backend.util.FileUtils;
import io.minio.MinioClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * 文件存储服务抽象方法
 *
 * @author: kou
 * @since: 2025/7/10 18:04
 */
@Slf4j
public abstract class AbstractFileStorageService implements FileStorageService {
    @Value("${minio.bucket-name}")
    protected String bucket;
    @Value("${file.storage.type}")
    protected String storageType;
    @Value("${file.storage.local-path}")
    protected String localRootPath;

    @Resource
    protected MinioClient minioClient;
    @Resource
    protected FileResourceDao fileResourceDao;

    @Resource
    protected FileAccessLogDao fileAccessLogDao;
    @Resource
    protected FileTagMappingDao fileTagMappingDao;
    @Resource
    protected FileTagDao fileTagDao;
    @Resource
    protected UserFileDao userFileDao;
    @Resource
    protected FileUploadChunkDao fileUploadChunkDao;

    @Override
    public StoreFileResultDTO storeFile(MultipartFile file, UploadFileRequestDTO requestDTO, String uploader) throws IOException {
        StoreFileResultDTO storeFileResultDTO = new StoreFileResultDTO();
        //计算文件md5
        String md5 = FileUtils.calculateMd5(file);

        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
        String originalName = file.getOriginalFilename();
        String uuidName = UUID.randomUUID() + "_" + originalName;

        FileResourceDO uploadResourceDO = new FileResourceDO();
        //检测文件是否已存在
        FileResourceDO dbFileResourceDO = fileResourceDao.selectOneByFileMd5(md5, storageType);

        //拼接相对路径
        String relativePath = Paths.get(uploader, datePath, uuidName).toString().replace("\\", "/");
        if (ObjectUtil.isNotEmpty(dbFileResourceDO)) {
            //重复上传校验
            if (userFileDao.exists(new LambdaQueryWrapper<UserFileDO>().eq(UserFileDO::getFileId, dbFileResourceDO.getId())
                    .eq(UserFileDO::getUserAccount, uploader))) {
                throw new CommonException(CommonErrorEnum.ERROR_FILE_REPEAT_UPLOAD);
            }
            // 已存在：只写标签映射，不写新文件表记录
            log.info("文件已存在：{},执行秒传", originalName);
            uploadResourceDO = dbFileResourceDO;
        } else {
            saveFileToDb(file, requestDTO, uploader, uploadResourceDO, relativePath, originalName, md5);
            storeFileResultDTO.setFileId(uploadResourceDO.getId());
        }

        //存储至文件表，文件标签关系
        List<FileTagDO> fileTagDOList = fileTagDao.selectList(new LambdaQueryWrapper<FileTagDO>().in(FileTagDO::getTagName, requestDTO.getTagNameList())
                .eq(FileTagDO::getUserAccount, uploader));
        if (ObjectUtil.isNotEmpty(fileTagDOList)) {
            for (FileTagDO fileTagDO : fileTagDOList) {
                boolean exists = fileTagMappingDao.exists(new LambdaQueryWrapper<FileTagMappingDO>()
                        .eq(FileTagMappingDO::getFileId, uploadResourceDO.getId())
                        .eq(FileTagMappingDO::getTagId, fileTagDO.getId())
                        .eq(FileTagMappingDO::getUserAccount, uploader));
                if (!exists) {
                    FileTagMappingDO fileTagMappingDO = saveTagMapping(uploader, uploadResourceDO, fileTagDO);
                    storeFileResultDTO.setTagId(fileTagMappingDO.getTagId());
                }
            }
        }

        UserFileDO userFileDO = saveUserFileRelation(uploader, uploadResourceDO);
        storeFileResultDTO.setUserFileId(userFileDO.getId());

        if (ObjectUtil.isEmpty(dbFileResourceDO)) {
            storeFileResultDTO.setNeedWriteFile(true);
        }
        storeFileResultDTO.setRelativePath(relativePath);
        storeFileResultDTO.setUploader(uploader);
        return storeFileResultDTO;
    }

    @Override
    public void saveErrorDeleteCompensateFileDbInfo(StoreFileResultDTO storeFileResultDTO) {
        if (storeFileResultDTO.isNeedWriteFile() && ObjectUtil.isNotEmpty(storeFileResultDTO.getFileId())) {
            //删除文件db数据
            fileResourceDao.deleteById(storeFileResultDTO.getFileId());
        }
        if (ObjectUtil.isNotEmpty(storeFileResultDTO.getUserFileId())) {
            //删除用户文件关系db数据
            userFileDao.deleteById(storeFileResultDTO.getUserFileId());
        }
        if (ObjectUtil.isNotEmpty(storeFileResultDTO.getTagId())) {
            //删除文件标签关系db数据
            fileTagMappingDao.delete(new LambdaQueryWrapper<FileTagMappingDO>().eq(FileTagMappingDO::getTagId, storeFileResultDTO.getTagId())
                    .eq(FileTagMappingDO::getUserAccount, storeFileResultDTO.getUploader())
                    .eq(FileTagMappingDO::getFileId, storeFileResultDTO.getFileId()));
        }
    }

    /**
     * 删除用户文件db数据
     *
     * @param userAccount 用户
     * @param fileId   文件id
     */
    public void deleteUserFileDb(String userAccount, String fileId) {
        //删表数据(文件表,文件用户关系,文件标签关系)
        //如果这个文件关联的所有用户都删除了，则删除文件表数据
        userFileDao.delete(new LambdaQueryWrapper<UserFileDO>().eq(UserFileDO::getFileId, fileId).eq(UserFileDO::getUserAccount, userAccount));
        if (userFileDao.selectCount(new LambdaQueryWrapper<UserFileDO>().eq(UserFileDO::getFileId, fileId)) == 0) {
            fileResourceDao.deleteById(fileId);
        }
        fileTagMappingDao.delete(new LambdaQueryWrapper<FileTagMappingDO>().eq(FileTagMappingDO::getFileId, fileId).eq(FileTagMappingDO::getUserAccount, userAccount));
    }

    private UserFileDO saveUserFileRelation(String uploader, FileResourceDO uploadResourceDO) {
        UserFileDO userFileDO = new UserFileDO();
        userFileDO.setUserAccount(uploader);
        userFileDO.setFileId(uploadResourceDO.getId());
        userFileDao.insert(userFileDO);
        return userFileDO;
    }

    private void saveFileToDb(MultipartFile file, UploadFileRequestDTO requestDTO, String uploader, FileResourceDO uploadResourceDO, String relativePath, String originalName, String md5) {
        uploadResourceDO.setStoragePath(relativePath);
        uploadResourceDO.setFileName(originalName);
        uploadResourceDO.setFileMd5(md5);
        uploadResourceDO.setFileSize(file.getSize());
        uploadResourceDO.setFileType(file.getContentType());
        uploadResourceDO.setUploader(uploader);
        uploadResourceDO.setRemark(requestDTO.getRemark());
        uploadResourceDO.setStorageType(storageType);
        fileResourceDao.insert(uploadResourceDO);
    }

    private FileTagMappingDO saveTagMapping(String uploader, FileResourceDO uploadResourceDO, FileTagDO fileTagDO) {
        FileTagMappingDO fileTagMappingDO = new FileTagMappingDO();
        fileTagMappingDO.setFileId(uploadResourceDO.getId());
        fileTagMappingDO.setTagId(fileTagDO.getId());
        fileTagMappingDO.setTagName(fileTagDO.getTagName());
        fileTagMappingDO.setUserAccount(uploader);
        fileTagMappingDao.insert(fileTagMappingDO);
        return fileTagMappingDO;
    }
}
